<template>
	<div class="app-container">
		<el-form ref="finalResultRef" :model="form" :rules="rules" label-width="120px">
			<el-row :gutter="20">
				<el-col :span="24">
					<el-row>
						<el-col :span="24" class="tab-title">
							{{ form.taskName }}评估任务
						</el-col>
					</el-row>
					<el-row>
						<el-col :span="8">
							<el-form-item label="任务编号" prop="taskNum">
								{{ form.taskNum }}
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="评估人" prop="">
								{{ form.evaluateUserName }}
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-button type="primary" @click="saveMiddleResult">存为中间结果</el-button>
						</el-col>
					</el-row>
					<el-row>
						<el-col :span="8">
							<el-form-item label="灾害类型" prop="">
								{{ form.disasterType }}
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="任务地区" prop="">
								{{ form.taskDistrict }}
							</el-form-item>
						</el-col>
					</el-row>
					<el-row>
						<el-col :span="24" class="tab-title">
							数据版本选择
						</el-col>
					</el-row>
					<el-row style="height: 50px;">
						<el-radio-group v-model="radio" @change="changeRadio" style="width: 100%;">
							<el-col :span="8" style="margin-left: 20px;">
								<el-radio label="1">
									<el-form-item label="钻孔数据" label-width="70px" style="margin-bottom: 0px;">
										<el-button v-if="isShowButton" @click="selectSlope" :disabled="isEditSel">选择</el-button>
										<el-link v-else v-if="isShowButton&&radio=='1'" type="primary" :underline="false" @click="selectSlope">{{ slopeVersion }}</el-link>
									</el-form-item>
								</el-radio>
							</el-col>
							<el-col :span="8">
								<el-radio label="2">
									<el-form-item label="导入钻孔数据" label-width="100px" style="margin-bottom: 0px;">
										<el-button v-if="isShowButton1" @click="handleImport" :disabled="isImport">导入</el-button>
										<el-link v-if="!isShowButton1&&radio=='2'" type="primary" :underline="false" @click="handleImport">{{ slopeVersion }}</el-link>
									</el-form-item>
								</el-radio>
							</el-col>
						</el-radio-group>
					</el-row>
					<el-row>
						<el-col :span="24" class="tab-title">
							分析评估
						</el-col>
					</el-row>
					<el-row>
						<el-col :span="4">
							<el-button type="primary" v-if="!mapView" @click="calculation">评估计算</el-button>
							<el-button type="primary" v-else @click="calculation">重新评估计算</el-button>
						</el-col>
						<el-col :span="10">
							<el-button plain v-if="mapView" @click="replaceModel">地图查看结果</el-button>
							<el-button plain v-if="mapView" @click="countResultProvinceArea">省统计危险性面积</el-button>
							<el-button plain v-if="mapView" @click="countResultCityArea">按市统计危险性面积</el-button>
						</el-col>
					</el-row>
					<el-row v-if="mapView">
						<p>评估结果：</p>
						<el-table :data="resultList">
							<el-table-column label="钻孔编号" align="center" prop="drillCode" />
							<el-table-column label="孔位经度（°）" align="center" prop="longitude" min-width="120" />
							<el-table-column label="孔位纬度（°）" align="center" prop="latitude" min-width="120" />
							<el-table-column label="土层名称" align="center" prop="geotechnicalDesignation" min-width="100" />
							<el-table-column label="土层厚度（m）" align="center" prop="layerThickness" min-width="110" />
							<el-table-column label="等效剪切波速（m/s）" align="center" prop="shearWaveVelocity" min-width="120" />
							<el-table-column label="临界等效剪切波速Vse（m/s）" align="center">
								<el-table-column label="抗震设防烈度（7度）" align="center" prop="intensity7" width="180" />
								<el-table-column label="抗震设防烈度（8度）" align="center" prop="intensity8" width="180" />
								<el-table-column label="抗震设防烈度（9度）" align="center" prop="intensity9" width="180" />
							</el-table-column>
							<el-table-column label="是否软土震陷" align="center">
								<el-table-column label="抗震设防烈度（7度）" align="center" prop="isSoft7" width="180">
									<template #default="{row}">
										<div>
											<span v-if="row.isSoft7==0">否</span>
											<span v-if="row.isSoft7==1">是</span>
										</div>
									</template>
								</el-table-column>
								<el-table-column label="抗震设防烈度（8度）" align="center" prop="isSoft8" width="180">
									<template #default="{row}">
										<div>
											<span v-if="row.isSoft8==0">否</span>
											<span v-if="row.isSoft8==1">是</span>
										</div>
									</template>
								</el-table-column>
								<el-table-column label="抗震设防烈度（9度）" align="center" prop="isSoft9" width="180">
									<template #default="{row}">
										<div>
											<span v-if="row.isSoft9==0">否</span>
											<span v-if="row.isSoft9==1">是</span>
										</div>
									</template>
								</el-table-column>
							</el-table-column>
						</el-table>
					</el-row>
				</el-col>
			</el-row>
		</el-form>

		<!-- 打开钻孔数据选择对话框 -->
		<el-dialog title="钻孔数据选择" v-model="openSlope" width="1000px" append-to-body>
			<p></p>
			<el-form :model="queryParamsSel" ref="querySelRef" :inline="true" v-show="showSearch" label-width="120px">
				<el-form-item label="版本号" prop="versionCode">
					<el-input v-model="queryParamsSel.versionCode" clearable />
				</el-form-item>
				<el-form-item label="上传人" prop="uploadUser">
					<el-input v-model="queryParamsSel.uploadUser" clearable />
				</el-form-item>
				<el-form-item label="上传日期">
					<el-col :span="10">
						<el-date-picker type="date" placeholder="选择日期" value-format="YYYY-MM-DD"
							v-model="queryParamsSel.uploadStartTime" style="width: 100%;" :disabled-date="startDisabledDate1"></el-date-picker>
					</el-col>
					<el-col class="line" :span="1">至</el-col>
					<el-col :span="10">
						<el-date-picker type="date" placeholder="选择日期" value-format="YYYY-MM-DD"
							v-model="queryParamsSel.uploadEndTime" style="width: 100%;" :disabled-date="endDisabledDate1"></el-date-picker>
					</el-col>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" icon="Search" @click="handleQuerySel">搜索</el-button>
					<el-button icon="Refresh" @click="resetQuerySel">重置</el-button>
				</el-form-item>
			</el-form>
			<el-table v-loading="loadingSel" ref="tableRef" :data="slopeDataList">
				<el-table-column type="expand" width="1">
					<template #default="props">
						<div class="expandTable">
							<h3>更多信息</h3>
							<p>数据名称: {{ props.row.dataName }}</p>
							<p>版本说明: {{ props.row.versionDesc }}（此处是版本说明，<span style="color:red">限制300字以内</span> ）</p>
							<p>数据说明: {{ props.row.dataDesc }}（此处是数据说明，<span style="color:red">限制300字以内</span> ）</p>
							<!--<p v-if="props.row.updateDesc">更新说明: {{ props.row.dataType }}</p>
            <p>使用系统: {{ props.row.useThisSystems }}
              <el-tooltip class="box-item" content="Right Center prompts info" placement="right">
                <el-tag>系统使用说明</el-tag>
              </el-tooltip>
            </p>
            <p>数据文件:
              <template v-for="item in props.row.dataFileList">
                <u style="color:#107ce5;cursor: pointer;" @click="handleDownload(item)">{{ item.name }}</u><br />
              </template>
            </p>
            <p>附件:
              <template v-for="item in props.row.attachmentList">
                <u style="color:#107ce5;cursor: pointer;" @click="handleDownload(item)">{{ item.name }}</u><br />
              </template>
            </p>-->
						</div>
					</template>
				</el-table-column>
				<el-table-column label="版本日期" align="center" prop="versionTime">
					<!--<template #default="scope">
						<el-button type="text" @click="edit(scope.row)">{{ scope.row.modelName }}
						</el-button>
					</template>-->
				</el-table-column>
				<el-table-column label="版本号" align="center" prop="versionCode" width="200" />
				<el-table-column label="版本级别（版本范围）" align="center" prop="dataRange" width="220" />
				<el-table-column label="上传日期" align="center" prop="uploadTime" />
				<el-table-column label="上传人" align="center" prop="uploadUser" />
				<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
					<template #default="scope">
						<el-button type="text" @click="handleMore(scope.row)">更多信息</el-button>
						<el-button type="text" @click="handleSelect(scope.row)">选择</el-button>
					</template>
				</el-table-column>
			</el-table>

			<pagination v-show="totalSel > 0" :total="totalSel" v-model:page="queryParamsSel.page"
				v-model:limit="queryParamsSel.rows" @pagination="getSlopeDataList" />

			<template #footer>
				<div class="dialog-footer">
					<el-button @click="cancel">取 消</el-button>
				</div>
			</template>
		</el-dialog>
		<!-- 导入对话框 -->
		<el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
			<p></p>
			<el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
				:disabled="upload.isUploading" :before-upload="handleFileBeforeUpload" :on-progress="handleFileUploadProgress"
				:on-error="handleFileUploadError" :on-success="handleFileSuccess" :auto-upload="false" :data="dataFile" drag>
				<el-icon class="el-icon--upload">
					<upload-filled />
				</el-icon>
				<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
				<template #tip>
					<div class="el-upload__tip text-center">
						<span>仅允许导入xls、xlsx格式文件。</span>
						<el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
							@click="importTemplate('软土震陷导入模板.xlsx')">下载模板</el-link>
					</div>
				</template>
			</el-upload>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitFileForm">确 定</el-button>
					<el-button @click="upload.open = false">取 消</el-button>
				</div>
			</template>
		</el-dialog>
		<!--空间分析-->
		<Spatialanalyst v-if="spatialanalystBool" :open="spatialanalystBool" :weakSoilAssessList="resultList"
			:taskId="route.query.taskId" @close="spatialanalystClose"></Spatialanalyst>
	</div>
</template>

<script setup name="indexAssessForm">
import Spatialanalyst from '@/map/components/spatialanalyst/index.vue';
import { getTaskModelDetail, saveAsMiddleResult, getSlopeData, count, selectVersionCode, countResultAreaByProvince, countResultAreaByCity } from "@/api/weakSoilAssess/indexAssess";
import { getToken } from "@/utils/auth";
import { ElLoading } from 'element-plus';

const route = useRoute();
const router = useRouter();
const openSlope = ref(false);
const { proxy } = getCurrentInstance();
const slopeDataList = ref([]);
const resultList = ref([]);
const isShowButton = ref(true);
const isShowButton1 = ref(true);
const slopeVersion = ref("0");
const mapView = ref(false);
const radio = ref('1');
const isEditSel = ref(false);
const isImport = ref(true);
const spatialanalystBool = ref(false);//是否开启空间分析
const loadingSel = ref(true);
const showSearch = ref(true);
const totalSel = ref(0);
const title = ref("");

/*** 用户导入参数 */
const upload = reactive({
	open: false,
	title: "",
	isUploading: false,
	headers: {
		token: "token " + getToken()
	},
	url: import.meta.env.VITE_APP_BASE_API + "/softSoil/importDrillData/" + route.query.taskId + "/" + slopeVersion.value
});
// 保留三位小数
const positive3decimals = (rule, value, callback) => {
	value = String(value)
	if (isNaN(value) || !value) {
		return callback(new Error());
	}
	var re = /^([0-9]+[\d]*(.[0-9]{3}))$/;
	if (!re.test(value)) {
		callback(new Error());
	} else {
		callback();
	}
}
// 保留两位小数
const positive2decimals = (rule, value, callback) => {
	value = String(value)
	if (isNaN(value) || !value) {
		return callback(new Error());
	}
	var re = /^([0-9]+[\d]*(.[0-9]{2}))$/;
	if (!re.test(value)) {
		callback(new Error());
	} else {
		callback();
	}
}
// (0,10]整数
const positive0_10integer = (rule, value, callback) => {
	value = String(value)
	if (isNaN(value) || !value) {
		return callback(new Error());
	}
	var re = /^([1-9]|10)$/;
	if (!re.test(value)) {
		callback(new Error());
	} else {
		callback();
	}
}
// [3,5]整数
const positive3_5integer = (rule, value, callback) => {
	value = String(value)
	if (isNaN(value) || !value) {
		return callback(new Error());
	}
	var re = /^([3-5])$/;
	if (!re.test(value)) {
		callback(new Error());
	} else {
		callback();
	}
}
const data = reactive({
	form: {},
	queryParamsSel: {
		page: 1,
		rows: 10,
	},
	rules: {
		taskCode: [{
			required: true,
			message: "任务编号不能为空",
			trigger: "blur"
		}],
		modelName: [{
			required: true,
			message: "模型名称不能为空",
			trigger: "blur"
		}],
		province: [{
			required: true,
			message: "省不能为空",
			trigger: "blur"
		}],
		provinceId: [{
			required: true,
			message: "省不能为空",
			trigger: "change"
		}],
		city: [{
			required: true,
			message: "市不能为空",
			trigger: "change"
		}],
		cityId: [{
			required: false,
			message: "市不能为空",
			trigger: "change"
		}],
		area: [{
			required: true,
			message: "区/县不能为空",
			trigger: "blur"
		}],
		areaId: [{
			required: true,
			message: "区/县 不能为空",
			trigger: "blur"
		}],
		smrsNumber1: [{
			required: true,
			message: "保留三位小数",
			trigger: "blur",
			validator: positive3decimals
		}],
		smrsNumber2: [{
			required: true,
			message: "保留两位小数",
			trigger: "blur",
			validator: positive2decimals
		}],
		deathNumber: [{
			required: true,
			message: "（0,10]之间的整数数",
			trigger: "blur",
			validator: positive0_10integer
		}],
		injuries: [{
			required: true,
			message: "[3,5]之间的整数",
			trigger: "blur",
			validator: positive3_5integer
		}],
	}
});

const { queryParamsSel, form, rules } = toRefs(data);

const startDisabledDate1 = (time) => {
  if (queryParamsSel.value.uploadEndTime) {
    return time.getTime() > new Date(queryParamsSel.value.uploadEndTime).getTime();
  }
  return false;
};
const endDisabledDate1 = (time) => {
  if (queryParamsSel.value.uploadStartTime) {
    return time.getTime() < new Date(queryParamsSel.value.uploadStartTime).getTime();
  }
  return false;
};

// 监听开始时间和结束时间的变化，更新对应的 disabledDate 函数
watch(queryParamsSel.value.uploadStartTime, (newVal) => {
  // 当开始时间改变时，更新结束时间的选择范围
  endDisabledDate1(newVal);
});

watch(queryParamsSel.value.uploadEndTime, (newVal) => {
  // 当结束时间改变时，更新开始时间的选择范围
  startDisabledDate1(newVal);
});

/** 获取模型详情 */
function getTaskModel() {
	const loading = ElLoading.service({
		lock: true,
		text: '加载中...',
		background: 'rgba(0, 0, 0, 0.7)',
	})
	let { taskId, dtcvId } = route.query
	getTaskModelDetail({ taskId, dtcvId: dtcvId || '' }).then(response => {
		loading.close()
		form.value = response.data;
		radio.value = response.data.dataFrom;
		if (response.data.dataFrom == "1") {
			isShowButton.value = true;
			isShowButton1.value = false;
			isEditSel.value = false;
			isImport.value = true;
		} else if (response.data.dataFrom == "2") {
			isShowButton.value = false;
			isShowButton1.value = true;
			isEditSel.value = true;
			isImport.value = false;
		}
		slopeVersion.value = response.data.versionCode;
		if (response.data.resultList.length != 0) {
			resultList.value = response.data.resultList;
			mapView.value = true;
		}
	}).catch(() => loading.close())
}
function changeRadio(value) {
	if (value == '1') {
		isEditSel.value = false;
		isImport.value = true;
		isShowButton.value = true;
		isShowButton1.value = false;
		slopeVersion.value=null
	} else {
		isShowButton.value = false;
		isShowButton1.value = true;
		isEditSel.value = true;
		isImport.value = false;
		slopeVersion.value='0'
	}
}
// 取消按钮
function cancel() {
	openSlope.value = false;
}
/** 搜索按钮操作 */
function handleQuerySel() {
	queryParamsSel.value.page = 1;
	getSlopeDataList();
}
function resetQuerySel() {
	queryParamsSel.value.uploadStartTime = "";
	queryParamsSel.value.uploadEndTime = "";
	proxy.resetForm("querySelRef");
	handleQuerySel();
}
//获取钻孔数据版本
function getSlopeDataList() {
	loadingSel.value = true;
	var province = route.query.taskDistrict;
	getSlopeData({ ...queryParamsSel.value, "typeCode": "y02ckxx,y04dcyxfc,y05bgzy06jqbscz,y10tgsycs", "province": province }).then(response => {
		loadingSel.value = false;
		slopeDataList.value = response.data.list;
		totalSel.value = response.data.total;
	});
}
//存为中间结果
function saveMiddleResult() {
	let data = { 
		taskId: form.value.taskId,
		versionCode: slopeVersion.value,
		dtcvId: route.query.dtcvId || '',
		resultStatus: route.query.dtcvId ? '1' : '2'
	};
	saveAsMiddleResult(data).then(response => {
		proxy.$modal.msgSuccess(response.data);
		getList();
	});
}
//评估计算中
var calculationLoading = null;
//评估计算
function calculation() {
	if (!slopeVersion.value) {
		proxy.$modal.msgWarning("请选择或导入钻孔数据");
		return
	}
  calculationLoading = ElLoading.service({
		lock: true,
		text: '计算中...',
		background: 'rgba(0, 0, 0, 0.7)',
	})
	spatialanalystBool.value = false;//关闭空间分析
	let data = {
		versionCode: slopeVersion.value,
		taskId: route.query.taskId,
		dataFrom: radio.value,
		dtcvId: route.query.dtcvId || '',
		resultStatus: route.query.dtcvId ? '1' : '2'
	}
	count(data).then(response => {
		resultList.value = response.data;
		// proxy.$modal.msgSuccess(response.message);
		if (resultList.value.length > 0) {
			mapView.value = true;
			spatialanalystBool.value = true;//开启空间分析--根据是否软土震陷点数据生成等值面
		} else {
			proxy.$modal.msgWarning("无评估结果");
      calculationLoading.close()
		}
	}).catch(() => {
		proxy.$modal.msgError("评估失败");
    calculationLoading.close()
	});
}
//完成空间分析
function spatialanalystClose() {
	spatialanalystBool.value = false;//关闭空间分析
  calculationLoading.close()
}
// 地图查看结果
function replaceModel() {
	router.push({
		path: "/rtAnalysisAssess/indexAssess/indexAssessMap",
		query: {
			metaTitle: "区域评估结果",
			dtcvId: resultList.value[0].dtcvId,
			taskDataId: route.query.taskId
		}
	})
}
// 更多数据
function handleMore(row) {
	proxy.$refs['tableRef'].toggleRowExpansion(row);
}
// 选择版本
function handleSelect(row) {
	isShowButton.value = false;
	slopeVersion.value = row.versionCode;
	selectVersionCode({ "versionCode": row.versionCode, "taskId": route.query.taskId, "disasterType": "3" }).then(response => {
		openSlope.value = false;
		proxy.$modal.msgSuccess(response.message);
	});
}
//钻孔数据选择
function selectSlope() {
	openSlope.value = true;
	queryParamsSel.value = {
		page: 1,
		rows: 10,
	},
	getSlopeDataList();
}
// 模板下载
function importTemplate(name) {
	proxy.download("/base/product/downloadTemplateExcel", {
		fileName: name
	}, name);
};
/** 提交上传文件 */
function submitFileForm() {
	proxy.$refs["uploadRef"].submit();
};
/** 打开导入表弹窗 */
function handleImport() {
	upload.title = "导入";
	upload.open = true;
}
/**文件上传前处理 */
function handleFileBeforeUpload(file) {
	proxy.$modal.loading("正在导入文件，请稍候...");
	return true
}
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
	upload.isUploading = true;
};
// 上传失败
function handleFileUploadError(err) {
	proxy.$modal.closeLoading();
	proxy.$modal.msgError("导入文件失败");
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
	upload.open = false;
	upload.isUploading = false;
	proxy.$modal.closeLoading();
	proxy.$refs["uploadRef"].handleRemove(file);
	proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 0 0;'>" + response.message + "</div>", "导入结果", {
		dangerouslyUseHTMLString: true
	});

	if (response.code == 200) {
		slopeVersion.value = response.data;
		isShowButton1.value = false;
	}
};
//按省统计危险性面积
function countResultProvinceArea() {
	const loading = ElLoading.service({
		lock: true,
		text: '计算中...',
		background: 'rgba(0, 0, 0, 0.7)',
	})
	countResultAreaByProvince({
		"taskId": route.query.taskId
	}).then(response => {
		proxy.$modal.alert(response.message);
		loading.close()
	}).catch(() => {
		proxy.$modal.alert("统计失败！");
		loading.close()
	});
}
//按市统计危险性面积
function countResultCityArea() {
	const loading = ElLoading.service({
		lock: true,
		text: '计算中...',
		background: 'rgba(0, 0, 0, 0.7)',
	})
	countResultAreaByCity({
		"taskId": route.query.taskId
	}).then(response => {
		console.log(response)
		proxy.$modal.alert(response.message);
		loading.close()
	}).catch(() => {
		proxy.$modal.alert("统计失败！");
		loading.close()
	});
}

getTaskModel();
</script>
<style scoped lang="scss">
@import '@/assets/styles/variables.module.scss';

.tab-title {
	font-size: 16px;
	font-weight: bold;
	border-left: 4px solid #0D9AFF;
	font-family: PingFangSC-Medium;
	padding-left: 10px;
	margin-bottom: 20px;
}

.line {
	text-align: center;
}

table td {
	border: 1px solid #c6c6c6;
}

form {
	width: 75%;
	margin: 0 auto;
}

:deep(.el-space) {
	.el-space__item {
		width: 100%;
	}
}

.success-btn-icon {
	.el-icon {
		color: $--color-success;
	}
}

.success-btn-icon.el-button--primary.is-plain {
	background-color: #ecf5ff !important;
	color: var(--el-color-primary) !important;
}</style>